<?php
namespace App\DBs;

use Illuminate\Support\Facades\DB;

class GuoDB extends BaseDB
{
    /**
     * 评论
     */

    public $tThing = 'thing';
    public $tGuoSet = 'guo_set';
    public $tGuoTree = 'guo_set_tree';
    public $tTask = 'guo_task';
    public $tCrop = 'guo_crop';
    public $tVideo = 'video';
    public $tUpload = 'upload';

    public function __construct()
    {
    }

    /**
     * 我的-果农-果树-列表
     */
    public function getMyTreeIndex($wx)
    {
        $query = DB::table($this->tThing)->where('del',0)->where('cate',1)->where('wx',$wx);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $year = ceil($model['year']/365);
            $out = ceil($model['out']/1000);
            $items[] = [
                'id'=>$model['id'], 'name'=>$model['name'],
                'serial'=>$model['serial'], 'code'=>$model['code'],
                'year'=>$year, 'out'=>$out, 'qrcodeUrl'=>'',
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 我的-果农-果树-未组合列表
     */
    public function getMyGroupNoIndex()
    {
        $query = DB::table($this->tThing)->where('del',0)->where('cate',1)->where('group',0);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $year = ceil($model['year']/365);
            $out = ceil($model['out']/1000);
            $items[] = [
                'id'=>$model['id'], 'name'=>$model['name'],
                'serial'=>$model['serial'], 'code'=>$model['code'],
                'year'=>$year, 'out'=>$out, 'qrcodeUrl'=>'',
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 我的-果农-养护组合-列表
     */
    public function getMyGroupIndex($wx)
    {
        $query = DB::table($this->tGuoSet)->where('del',0)->where('wx',$wx);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $trees = $this->getTreesByGroup($model['id']);
            $items[] = [
                'id'=>$model['id'], 'name'=>$model['name'], 'trees'=>$trees,
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 获取果树，通过组合
     */
    public function getTreesByGroup($group)
    {
        $items = array();
        $models = DB::table($this->tGuoTree)->where('del',0)->where('group',$group)->get();
        if (!count($models)) { return $items; }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            $trees = DB::table($this->tThing)->where('id',$model['tree'])->get();
            $tree = count($trees) ? $this->jsonToArr($trees[0]) : '';
            $treeName = $tree ? $tree['serial'] : '';
            $items[] = [
                'id'=>$model['id'], 'tree'=>$model['tree'], 'treeName'=>$treeName,
            ];
        }
        return $items;
    }

    /**
     * 设置组合
     */
    public function setGroupAdd($wx,$groupName)
    {
        $resGroups = DB::table($this->tGuoSet)->where('del',0)
            ->where('wx',$wx)->where('name',$groupName)->get();
        if (count($resGroups)) { return array('code'=>'-3','msg'=>'已存在'); }
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->tGuoSet)->insertGetId([
                'name'=>$groupName, 'wx'=>$wx, 'created_at'=>time(),
            ]);
            if (!$lastId) {
                return array('code'=>'-2','msg'=>'新增失败');
            }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 组合新增果树
     */
    public function setGroupAddTree($wx,$gid,$tid)
    {
        $gts = DB::table($this->tGuoTree)->where('del',0)->where('wx',$wx)
            ->where('group',$gid)->where('tree',$tid)->get();
        if (count($gts)) { return array('code'=>'-3','msg'=>'已存在'); }
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->tGuoTree)->insertGetId([
                'wx'=>$wx, 'group'=>$gid,  'tree'=>$tid, 'created_at'=>time(),
            ]);
            if (!$lastId) {
                return array('code'=>'-2','msg'=>'新增失败');
            }
            $resDb = DB::table($this->tThing)->where('id',$tid)->update(['group'=>$lastId]);
            if (!$resDb) {
                return array('code'=>'-2','msg'=>'更新失败');
            }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 组合删除果树
     */
    public function setGroupDelTree($id)
    {
        $gts = DB::table($this->tGuoTree)->where('del',0)->where('id',$id)->get();
        if (!count($gts)) { return array('code'=>'-3','msg'=>'不存在'); }
        $gt = $this->jsonToArr($gts[0]); $tid = $gt['tree'];
        //开启事务
        DB::beginTransaction();
        try {
            $resDb = DB::table($this->tGuoTree)->where('id',$id)->update(['del'=>1,'updated_at'=>time()]);
            if (!$resDb) {
                return array('code'=>'-2','msg'=>'删除失败');
            }
            $resDb = DB::table($this->tThing)->where('id',$tid)->update(['group'=>0]);
            if (!$resDb) {
                return array('code'=>'-2','msg'=>'更新失败');
            }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-果农-任务列表
     */
    public function getMyTaskIndex($wx)
    {
        $query = DB::table($this->tTask)->where('del',0)->where('wx',$wx);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array(); $videoObj = new VideoDB();
        foreach ($models as $model) {
            $groups = DB::table($this->tGuoSet)->where('id',$model['gid'])->get();
            $group = count($groups) ? $this->jsonToArr($groups[0]) : '';
            $groupName = $group ? $group['name'] : '';
            $resVideo = $videoObj->getOneById($model['vid']);
            if ($resVideo['code']==0) {
                $cover = $resVideo['data']['vcover'];
                $link =$resVideo['data']['vlink'];
            } else {
                $cover = ''; $link = '';
            }
            $addTime = date('Y-m-d H:i',$model['created_at']);
            $items[] = [
                'id'=>$model['id'], 'title'=>$model['title'], 'groupName'=>$groupName,
                'cover'=>$cover, 'link'=>$link, 'addTime'=>$addTime,
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 我的-果农-任务新增
     */
    public function setTaskAdd($wx,$title,$gid,$link)
    {
        $uploads = DB::table($this->tUpload)->where('del',0)->where('wx',$wx)->where('link',$link)->get();
        if (!count($uploads)) { return array('code'=>'-2','msg'=>'视频不存在'); }
        $upload = $this->jsonToArr($uploads[0]);
        $cover = env('DOMAIN').'/'.$upload['cover'];
        $link = env('DOMAIN').'/'.$upload['link'];
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->tTask)->insertGetId([
                'wx'=>$wx, 'title'=>$title, 'gid'=>$gid, 'created_at'=>time(),
            ]);
            if (!$lastId) { return array('code'=>'-3','msg'=>'任务错误'); }
            $resVideo = DB::table($this->tVideo)->insertGetId([
                'wx'=>$wx, 'title'=>$title, 'type'=>4, 'thing'=>$lastId,
                'cover'=>$cover, 'link'=>$link, 'created_at'=>time(),
            ]);
            if (!$resVideo) { return array('code'=>'-4','msg'=>'视频错误'); }
            $resTask = DB::table($this->tTask)->where('id',$lastId)->update(['vid'=>$resVideo]);
            if (!$resTask) { return array('code'=>'-5','msg'=>'更新错误'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-果农-任务删除
     */
    public function setTaskDel($id)
    {
        $resOnes = DB::table($this->tTask)->where('id',$id)->get();
        $resOne = count($resOnes) ? $this->jsonToArr($resOnes[0]) : '';
        $vid = $resOne ? $resOne['vid'] : 0;
        //开启事务
        DB::beginTransaction();
        try {
            $resTask = DB::table($this->tTask)->where('id',$id)->update(['del'=>1,'updated_at'=>time()]);
            if (!$resTask) { return array('code'=>'-2','msg'=>'任务错误'); }
            $resVideo = DB::table($this->tVideo)->where('id',$vid)->update(['del'=>1,'updated_at'=>time()]);
            if (!$resVideo) { return array('code'=>'-3','msg'=>'视频错误'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-果农-收成列表
     */
    public function getMyCropIndex($wx)
    {
        $query = DB::table($this->tCrop)->where('del',0)->where('wx',$wx);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array(); $videoObj = new VideoDB();
        foreach ($models as $model) {
            $trees = DB::table($this->tThing)->where('id',$model['tid'])->get();
            $tree = count($trees) ? $this->jsonToArr($trees[0]) : '';
            $treeName = $tree ? $tree['name'] : '';
            $resVideo = $videoObj->getOneById($model['vid']);
            if ($resVideo['code']==0) {
                $cover = $resVideo['data']['vcover'];
                $link =$resVideo['data']['vlink'];
            } else {
                $cover = ''; $link = '';
            }
            $addTime = date('Y-m-d H:i',$model['created_at']);
            $weight = ceil($model['weight']/1000);
            $price = $model['price']/100;
            $items[] = [
                'id'=>$model['id'], 'title'=>$model['title'], 'treeName'=>$treeName,
                'weight'=>$weight, 'guke'=>$model['guke'], 'price'=>$price,
                'cover'=>$cover, 'link'=>$link, 'addTime'=>$addTime,
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 我的-果农-收成新增
     */
    public function setCropAdd($wx,$title,$tid,$link)
    {
        $uploads = DB::table($this->tUpload)->where('del',0)->where('wx',$wx)->where('link',$link)->get();
        if (!count($uploads)) { return array('code'=>'-2','msg'=>'视频不存在'); }
        $upload = $this->jsonToArr($uploads[0]);
        $cover = env('DOMAIN').'/'.$upload['cover'];
        $link = env('DOMAIN').'/'.$upload['link'];
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->tCrop)->insertGetId([
                'wx'=>$wx, 'title'=>$title, 'tid'=>$tid, 'created_at'=>time(),
            ]);
            if (!$lastId) { return array('code'=>'-3','msg'=>'任务错误'); }
            $resVideo = DB::table($this->tVideo)->insertGetId([
                'wx'=>$wx, 'title'=>$title, 'type'=>4, 'thing'=>$lastId,
                'cover'=>$cover, 'link'=>$link, 'created_at'=>time(),
            ]);
            if (!$resVideo) { return array('code'=>'-4','msg'=>'视频错误'); }
            $resTask = DB::table($this->tCrop)->where('id',$lastId)->update(['vid'=>$resVideo]);
            if (!$resTask) { return array('code'=>'-5','msg'=>'更新错误'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-果农-收成更新
     */
    public function setCropModify($id,$guke,$weight,$price)
    {
        $resOnes = DB::table($this->tCrop)->where('id',$id)->get();
        if (!count($resOnes)) { return array('code'=>'-2','msg'=>'不存在'); }
        $price = $price*100;
        //开启事务
        DB::beginTransaction();
        try {
            $resDb = DB::table($this->tCrop)->where('id',$id)
                ->update(['guke'=>$guke, 'weight'=>$weight, 'price'=>$price, 'updated_at'=>time()]);
            if (!$resDb) { return array('code'=>'-3','msg'=>'收成错误'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-果农-收成删除
     */
    public function setCropDel($id)
    {
        $resOnes = DB::table($this->tCrop)->where('id',$id)->get();
        $resOne = count($resOnes) ? $this->jsonToArr($resOnes[0]) : '';
        $vid = $resOne ? $resOne['vid'] : 0;
        //开启事务
        DB::beginTransaction();
        try {
            $resTask = DB::table($this->tCrop)->where('id',$id)->update(['del'=>1,'updated_at'=>time()]);
            if (!$resTask) { return array('code'=>'-2','msg'=>'任务错误'); }
            $resVideo = DB::table($this->tVideo)->where('id',$vid)->update(['del'=>1,'updated_at'=>time()]);
            if (!$resVideo) { return array('code'=>'-3','msg'=>'视频错误'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 我的-用户-交易榜
     */
    public function getMyTradeIndex()
    {
        $query = DB::table($this->tCrop)->where('del',0);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) { return array('code'=>'-1','msg'=>'no data'); }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $addTime = date('Y-m-d',$model['created_at']);
            $weight = ceil($model['weight']/1000);
            $price = $model['price']/100;
            $guke = $model['guke'] ? $model['guke'] : '-';
            $items[] = [
                'id'=>$model['id'], 'weight'=>$weight, 'guke'=>$guke,
                'price'=>$price, 'addTime'=>$addTime,
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }
}